<?php

namespace Cekurte;
	
/**
 * Classe responsável pela autenticação de usuários do sistema
 * 
 * @author 	João Paulo Cercal
 * @version 1.0
 */
class Auth implements \Zend_Auth_Adapter_Interface
{
	/**
	 * @var string Usuário do Sistema
	 */
    private $username;
	
	/**
	 * @var string Senha do usuário
	 */
    private $password;
    
    /**
     * Método construtor
     * 
     * @param 	mixed $usuario usuário do sistema.
     * @param 	mixed $senha senha do usuário do sistema.
     * 
     * @author 	João Paulo Cercal
     * @version 1.0
     */
    public function __construct( $username, $password ) 
    {
        if( !empty($username) and !empty($password) )
        {
            $this->username	= $username;
            $this->password	= $password;
        }
    }
    
	/**
     * Método de autenticação
     * 
     * @author 	João Paulo Cercal
     * @version 1.0
     * 
     * @return Zend_Auth_Result
     */
    public function authenticate() 
    {
		try
		{	
			$userModel 	= new \Application_Model_User();
			
			$user 		= $userModel->login( $this->username, $this->password );
			
			$registry 	= \Zend_Registry::getInstance();
			
			$translate	= $registry->Zend_Translate;
			
			if( $user instanceof \Entities\User )
			{	
				$userIdentity 			= new \stdClass();
				$userIdentity->id 		= $user->getId();
				$userIdentity->username = $user->getUsername();
				$userIdentity->token 	= md5( uniqid(rand(), true) );
				
				$identity 				= new \stdClass();
				$identity->user 		= $userIdentity;
				
				/** @todo Outras informacoes de identidade que seriam interessantes: nome, tema, idioma */
				
				return new \Zend_Auth_Result( \Zend_Auth_Result::SUCCESS, $identity, array(
					'message' => $translate->_('library.cekurte.auth.success')
				));	
			}
			else
			{
				return new \Zend_Auth_Result(\Zend_Auth_Result::FAILURE, array(), array(
					'message' => $translate->_('library.cekurte.auth.invalid.username_password')
				));
			}
		}
		catch( Exception $e ) 
		{
			return new \Zend_Auth_Result(\Zend_Auth_Result::FAILURE_CREDENTIAL_INVALID, array(), array(
				'message' => $translate->_('library.cekurte.auth.error')
			));
		}
    }
}

?>
